<template>
  <CollapseContainer :title="t('sys.account.basicTab')" :canExpan="false" class="overflow-x-hidden">
    <ARow :gutter="24" class="mt-3">
      <ACol :span="14">
        <BasicForm @register="register" />
      </ACol>
      <ACol :span="10">
        <div class="change-avatar mt-6">
          <CropperAvatar
            :value="avatar"
            :btnText="t('sys.account.changeAvatar')"
            :btnProps="{ preIcon: 'ant-design:cloud-upload-outlined' }"
            @change="updateAvatar"
            width="150"
          />
        </div>
      </ACol>
    </ARow>
    <div class="ml-30">
      <Button type="primary" @click="handleSubmit">
        <Icon icon="ant-design:check-outlined" /> {{ t('sys.account.updateBtn') }}
      </Button>
      <!-- 增加按钮之间间隔 -->
      <Button type="primary" @click="handlePullClick" :disabled="isPulling" class="ml-3">
        <Icon icon="ant-design:check-outlined" /> {{ t('sys.account.pullBtn') }}
      </Button>
    </div>

    <!-- 全屏加载蒙层 -->
    <div v-if="showLoading" class="loading-overlay">
      <div class="loading-content">
        <Spin size="large" tip="正在获取数据，请稍后..." />
      </div>
    </div>
  </CollapseContainer>
</template>
<script lang="ts" setup>
  import { computed, onMounted, ref } from 'vue';
  import { Button, Row, Col, Modal, Spin } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { CollapseContainer } from '/@/components/Container';
  import { CropperAvatar } from '/@/components/Cropper';
  import headerImg from '/@/assets/images/header.jpg';
  import { useUserStore } from '/@/store/modules/user';
  import { userInfo, infoSaveBase, updateBasicInformation } from '/@/api/sys/user';
  import { getBaseInfo } from '/@/api/sys/desktopApi';
  import axios from 'axios';
  // import { uploadApi } from '/@/api/sys/upload';

  const { t } = useI18n();
  const { showMessage } = useMessage();
  const avatarBase64 = ref<String>('');
  const userStore = useUserStore();
  const ARow = Row;
  const ACol = Col;

  // 新增状态变量
  const isPulling = ref(false);
  const showLoading = ref(false);

  const userInfoSchemas: FormSchema[] = [
    {
      field: 'patientName',
      component: 'Input',
      label: t('sys.account.userName'),
      colProps: { span: 18 },
    },
    {
      field: 'sex',
      component: 'Input',
      label: t('sys.account.userSex'),
      colProps: { span: 18 },
    },
    {
      field: 'age',
      component: 'Input',
      label: t('sys.account.age'),
      colProps: { span: 18 },
    },
    {
      field: 'ethnic',
      component: 'Input',
      label: t('sys.account.ethnic'),
      colProps: { span: 18 },
    },
    {
      field: 'origin',
      component: 'Input',
      label: t('sys.account.origin'),
      colProps: { span: 18 },
    },
    {
      field: 'address',
      component: 'Input',
      label: t('sys.account.address'),
      colProps: { span: 18 },
    },
    {
      field: 'identificationNumber',
      component: 'Input',
      label: t('sys.account.identificationNumber'),
      colProps: { span: 18 },
    },
    {
      field: 'id',
      component: 'Input',
      label: t('sys.account.id'),
      colProps: { span: 18 },
      dynamicDisabled: true,
      show: false,
    },
  ];

  const [register, { setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: userInfoSchemas,
    showActionButtonGroup: false,
  });

  onMounted(async () => {
    const data = userStore.getUserInfo;
    const baseInfo = await getBaseInfo({ phone: data.userCode });
    console.log('baseInfo', baseInfo);
    setFieldsValue({
      patientName: baseInfo.patientName,
      sex: baseInfo.sex,
      patientPhone: baseInfo.patientPhone,
      address: baseInfo.address,
      age: baseInfo.age,
      ethnic: baseInfo.ethnic,
      origin: baseInfo.origin,
      identificationNumber: baseInfo.identificationNumber,
      id: baseInfo.id,
    });
  });

  const avatar = computed(() => {
    const { avatarUrl } = userStore.getUserInfo;
    return avatarUrl || headerImg;
  });

  function updateAvatar(source: string) {
    avatarBase64.value = source;
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      if (avatarBase64.value != '') {
        data.avatarBase64 = avatarBase64.value;
      }
      console.log('submit', data);
      data.patientPhone = userStore.getUserInfo.loginCode;

      const res = await updateBasicInformation(data);
      // const userInfoRes = await userInfo();
      // const user = userInfoRes.user;
      // if (avatarBase64.value != '') {
      //   user.avatarUrl = avatarBase64.value;
      // }
      // userStore.setUserInfo(userInfoRes);
      showMessage(res.message);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  // 新增按钮点击处理函数
  async function handlePullClick() {
    // 立即禁用按钮
    isPulling.value = true;

    // 显示确认对话框
    Modal.confirm({
      title: '授权确认',
      content: '您将授权我们从众阳云健康获取您的基本信息，是否继续？',
      onOk: async () => {
        // 用户确认后，显示加载蒙层并调用handlePull
        showLoading.value = true;
        try {
          await handlePull();
        } finally {
          // 无论成功失败，都关闭加载蒙层
          showLoading.value = false;
          // 恢复按钮可用状态
          isPulling.value = false;
        }
      },
      onCancel: () => {
        // 用户取消，恢复按钮可用状态
        isPulling.value = false;
        Modal.destroyAll();
      },
    });
  }

  async function handlePull() {
    // showUpdateModal.value = true;
    // 获取体重上报的最后时间，还没做
    try {
      const data = await validate();
      data.patientPhone = userStore.getUserInfo.loginCode;
      // 拉取数据
      const id_1 = data.identificationNumber;
      // alert(id_1);
      if (!id_1) {
        showMessage('用户身份证号为空');
        return;
      }
      const remote_res = await axios.post(
        `https://hgdzhyypt.msuncloud.cn:20145/main/execute-task`,
        { user_id: id_1, task_name: 'summarize_zy_information_records' },
        {
          timeout: 150000,
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );
      console.log('API 响应:', remote_res.data);
      const newInfo = remote_res.data.data;
      // 设置id
      newInfo.id = data.id;
      newInfo.patientPhone = userStore.getUserInfo.loginCode;
      newInfo.patientName = data.patientName;
      newInfo.identificationNumber = id_1;
      // 设置newInfo中的体重和身高为number格式，如果为空字符串则设置为空
      newInfo.weight = newInfo.weight ? parseFloat(newInfo.weight) : null;
      newInfo.height = newInfo.height ? parseFloat(newInfo.height) : null;
      newInfo.ethnic = newInfo.ethnic ? newInfo.ethnic : null;
      newInfo.origin = newInfo.origin ? newInfo.origin : null;
      newInfo.address = newInfo.address ? newInfo.address : null;
      newInfo.sex = newInfo.sex ? newInfo.sex : null;
      newInfo.age = newInfo.age ? parseInt(newInfo.age) : null;
      newInfo.illness = newInfo.illness ? newInfo.illness : null;
      // 保存数据
      const res = await updateBasicInformation(newInfo);
      // const userInfoRes = await userInfo();
      // const user = userInfoRes.user;
      // if (avatarBase64.value != '') {
      //   user.avatarUrl = avatarBase64.value;
      // }
      // userStore.setUserInfo(userInfoRes);
      showMessage(res.message);
      Modal.destroyAll();
      // 更新表单数据
      setFieldsValue({
        // patientName保持不变
        patientName: newInfo.patientName,
        sex: newInfo.sex,
        patientPhone: newInfo.patientPhone,
        address: newInfo.address,
        age: newInfo.age,
        ethnic: newInfo.ethnic,
        origin: newInfo.origin,
        identificationNumber: newInfo.identificationNumber,
        id: newInfo.id,
      });
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      } else {
        showMessage('数据获取失败，请稍后重试');
      }
      console.log('error', error);
    }
  }
</script>
<style lang="less" scoped>
  .change-avatar {
    img {
      display: block;
      margin-bottom: 15px;
      border-radius: 50%;
    }
  }

  // 全屏加载蒙层样式
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
  }

  .loading-content {
    background-color: white;
    padding: 40px;
    border-radius: 8px;
    text-align: center;
  }
</style>
